Solvers


In [2]:
from sympy import *
init_printing()

For each exercise, fill in the function according to its docstring.


In [3]:
a, b, c, d, x, y, z, t = symbols('a b c d x y z t')
f, g, h = symbols('f g h', cls=Function)

Algebraic Equations

Write a function that computes the quadratic equation.


In [5]:
def quadratic():
    return solve(a*x**2 + b*x + c, x)
quadratic()


Out[5]:
$$\begin{bmatrix}\frac{- b + \sqrt{- 4 a c + b^{2}}}{2 a}, & - \frac{b + \sqrt{- 4 a c + b^{2}}}{2 a}\end{bmatrix}$$

Write a function that computes the general solution to the cubic $x^3 + ax^2 + bx + c$.


In [6]:
def cubic():
    return solve(x**3 + a*x**2 + b*x + c, x)
cubic()


Out[6]:
$$\begin{bmatrix}- \frac{1}{3} a + \frac{- \frac{1}{9} a^{2} + \frac{1}{3} b}{\sqrt[3]{\frac{1}{27} a^{3} - \frac{1}{6} a b + \frac{1}{2} c + \sqrt{\left(- \frac{1}{9} a^{2} + \frac{1}{3} b\right)^{3} + \frac{1}{4} \left(\frac{2}{27} a^{3} - \frac{1}{3} a b + c\right)^{2}}}} - \sqrt[3]{\frac{1}{27} a^{3} - \frac{1}{6} a b + \frac{1}{2} c + \sqrt{\left(- \frac{1}{9} a^{2} + \frac{1}{3} b\right)^{3} + \frac{1}{4} \left(\frac{2}{27} a^{3} - \frac{1}{3} a b + c\right)^{2}}}, & - \frac{1}{3} a + \frac{- \frac{1}{9} a^{2} + \frac{1}{3} b}{\left(- \frac{1}{2} - \frac{1}{2} \sqrt{3} \mathbf{\imath}\right) \sqrt[3]{\frac{1}{27} a^{3} - \frac{1}{6} a b + \frac{1}{2} c + \sqrt{\left(- \frac{1}{9} a^{2} + \frac{1}{3} b\right)^{3} + \frac{1}{4} \left(\frac{2}{27} a^{3} - \frac{1}{3} a b + c\right)^{2}}}} - \left(- \frac{1}{2} - \frac{1}{2} \sqrt{3} \mathbf{\imath}\right) \sqrt[3]{\frac{1}{27} a^{3} - \frac{1}{6} a b + \frac{1}{2} c + \sqrt{\left(- \frac{1}{9} a^{2} + \frac{1}{3} b\right)^{3} + \frac{1}{4} \left(\frac{2}{27} a^{3} - \frac{1}{3} a b + c\right)^{2}}}, & - \frac{1}{3} a + \frac{- \frac{1}{9} a^{2} + \frac{1}{3} b}{\left(- \frac{1}{2} + \frac{1}{2} \sqrt{3} \mathbf{\imath}\right) \sqrt[3]{\frac{1}{27} a^{3} - \frac{1}{6} a b + \frac{1}{2} c + \sqrt{\left(- \frac{1}{9} a^{2} + \frac{1}{3} b\right)^{3} + \frac{1}{4} \left(\frac{2}{27} a^{3} - \frac{1}{3} a b + c\right)^{2}}}} - \left(- \frac{1}{2} + \frac{1}{2} \sqrt{3} \mathbf{\imath}\right) \sqrt[3]{\frac{1}{27} a^{3} - \frac{1}{6} a b + \frac{1}{2} c + \sqrt{\left(- \frac{1}{9} a^{2} + \frac{1}{3} b\right)^{3} + \frac{1}{4} \left(\frac{2}{27} a^{3} - \frac{1}{3} a b + c\right)^{2}}}\end{bmatrix}$$

Differential Equations

A population that grows without bound is modeled by the differential equation

$$f'(t)=af(t)$$

Solve this differential equation using SymPy.


In [7]:
dsolve(f(t).diff(t) - a*f(t), f(t))


Out[7]:
$$\operatorname{f}{\left (t \right )} = C_{1} e^{a t}$$

If the population growth is bounded, it is modeled by

$$f'(t) = f(t)(1 - f(t))$$

Solve this differential equation using SymPy.


In [8]:
dsolve(f(t).diff(t) - f(t)*(1 - f(t)), f(t))


Out[8]:
$$\log{\left (\operatorname{f}{\left (t \right )} -1 \right )} - \log{\left (\operatorname{f}{\left (t \right )} \right )} = C_{1} - t$$